<script setup lang="ts">
import type { EChartsOption } from 'echarts';

import { onMounted, onUnmounted, ref, watch } from 'vue';

import * as echarts from 'echarts';

interface ChartProps {
  chartData: {
    name: string; // 数据名称
    value: number; // 数据值
  }[];
}

const props = defineProps<ChartProps>();

const chartRef = ref<HTMLElement>();
let chart: echarts.ECharts | null = null;

const getOptions = (): EChartsOption => ({
  backgroundColor: 'transparent',
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)',
  },

  legend: {
    orient: 'vertical',
    left: '0%',
    textStyle: {
      color: '#fff',
    },
    // formatter: function (name) {
    //   return name.length > 5 ? name.slice(0, 5) + '...' : name;
    // }
  },
  series: [
    {
      name: '数据统计',
      type: 'pie',
      radius: [20, 80],
      center: ['67%', '50%'],
      roseType: 'area',
      itemStyle: {
        borderRadius: 5
      },
      data: props.chartData,
      label: {
        backgroundColor: 'transparent', // 去掉白底
        color: '#fff', // 保证字体为白色
        fontSize: 12,
        formatter: function (params) {
          const name = params.name || '';
          return name.length > 5 ? name.slice(0, 5) + '...' : name;
        }
      },
    },
  ],
});

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;
  chart = echarts.init(chartRef.value);
  chart.setOption(getOptions());
};

// 监听数据变化
watch(
  () => props.chartData,
  () => {
    chart?.setOption(getOptions());
  },
  { deep: true },
);

// 监听窗口大小变化
const handleResize = () => {
  chart?.resize();
};

onMounted(() => {
  initChart();
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  chart?.dispose();
});
</script>

<template>
  <div ref="chartRef" style="width: 100%; height: 260px"></div>
</template>
